package com.vipsoft.ws.interceptor;

import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

import javax.xml.soap.SOAPException;
import java.util.List;

@Component
public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
    private static final String USERNAME = "root";
    private static final String PASSWORD = "admin";

    public AuthInterceptor() {
        // 定义在哪个阶段进行拦截
        super(Phase.PRE_PROTOCOL);
    }

    @Override
    public void handleMessage(SoapMessage soapMessage) throws Fault {
        List<Header> headers = soapMessage.getHeaders();
        String username = null;
        String password = null;
        if (headers == null || headers.isEmpty()) {
            throw new Fault(new IllegalArgumentException("找不到Header，无法验证用户信息"));
        }
        // 获取用户名,密码
        for (Header header : headers) {
            SoapHeader soapHeader = (SoapHeader) header;
            Element e = (Element) soapHeader.getObject();
            username = e.getAttribute("username");
            password = e.getAttribute("password");
            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
                throw new Fault(new IllegalArgumentException("用户信息为空"));
            }
        }
        // 校验用户名密码
        if (!(USERNAME.equals(username) && PASSWORD.equals(password))) {
            SOAPException soapExc = new SOAPException("认证失败");
            System.err.println("用户认证信息错误");
            throw new Fault(soapExc);
        }
    }
}